package com.app;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.app.adapter.NewsListAdapter;
import com.app.bean.NewsListBean;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class NewsListActivity extends AppCompatActivity {

    private ListView lvNews;
    private NewsListAdapter adapter;
    private NewsListBean newsListBean;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_list);

        id = getIntent().getStringExtra("id");
        initView();
        initData();
        initEvent();

    }


    private void initEvent() {
        lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(NewsListActivity.this, NewsDetailActivity.class);
                intent.putExtra("id",newsListBean.getList().get(position).getId());
                startActivity(intent);
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewsListActivity.this,MainActivity.class));

            }
        });
    }


    private void initData() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);//请求队列
        String url = "http://www.xhjjyst.com/freshmenapp/news/list";//请求地址
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() //请求参数
        {
            @Override
                    public void onResponse(JSONObject jsonObject) {
                Gson gson = new Gson();
                newsListBean = gson.fromJson(jsonObject.toString(),NewsListBean.class);
                adapter = new NewsListAdapter(NewsListActivity.this, newsListBean.getList());
                lvNews.setAdapter(adapter);
            }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(NewsListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();

            }
        });
        requestQueue.add(request);//加入队列

    }
    private void initView() {
        lvNews = findViewById(R.id.lv_news);

    }
}